package com.example.wan1.view;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.wan1.R;
import com.example.wan1.base.adapter.BaseFragmentPagerAdapter;
import com.example.wan1.bus.RxBus;
import com.example.wan1.interfaces.RvScrollListener;
import com.example.wan1.utils.ColorTheme;
import com.example.wan1.utils.SPUtils;
import com.example.wan1.utils.StatusBarUtil;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.homenew.NewHomeFragment;
import com.example.wan1.view.login.UserManager;
import com.example.wan1.view.mine.MineFragment;
import com.example.wan1.view.project.ProjectsFragment;
import com.example.wan1.view.system.SystemFragment;
import com.example.wan1.view.wechat.WxFragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

/***
 * 首页
 * 1.bug:当我们上滑，本来应该隐藏布局的，因为我们使用的是linearLayout导致会出现空白的布局，改成FrameLayout或者CoordinatorLayout都行，
 * 同时把tab的位置放到下面
 */
public class MainActivity extends AppCompatActivity implements RvScrollListener {

    @BindView(R.id.main_vp)
    ViewPager mVpMain;
    @BindView(R.id.main_tab)
    TabLayout mTabMain;
    @BindView(R.id.fab_top)
    FloatingActionButton mFabTop;

    private List<Fragment> mFragments;
    private List<String> mTitles;
    private BaseFragmentPagerAdapter mAdapter;

    //未选择的图标
    private int[] tabIcons = new int[]{
            R.mipmap.main_unselected,
            R.mipmap.system_unselected,
            R.mipmap.project_unselected,
            R.mipmap.square_unselected,
            R.mipmap.mine_unselected
    };
    //已选择的图标
    private int[] tabIconSelected = new int[]{
            R.mipmap.main_selected,
            R.mipmap.system_selected,
            R.mipmap.project_selected,
            R.mipmap.square_selected,
            R.mipmap.mine_selected
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ColorTheme newTheme = new ColorTheme(this);
        newTheme.loadTheme();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initFragment();
        initViewPager();

        RxBus.getDefault().subscribe(this, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String s) {
                if (s.equals("theme")) {
                    /*startActivity(new Intent(MainActivity.this, MainActivity.class));
                    finish();*/
                    recreate();
                    mVpMain.setCurrentItem(0);
                } else if (s.equals("theme_color")) {
                    recreate();
                    mVpMain.setCurrentItem(0);
                    //如果颜色更新当前的选中的tab也需要更改颜色
                    int selectedTabPosition = mTabMain.getSelectedTabPosition();
                    TabLayout.Tab tabAt = mTabMain.getTabAt(selectedTabPosition);
                    TextView tv = tabAt.getCustomView().findViewById(R.id.tab_text);
                    ImageView iv = tabAt.getCustomView().findViewById(R.id.tab_image);
                    String theme_color = (String) SPUtils.get(MainActivity.this, "theme_color", "");
                    iv.setColorFilter(Color.parseColor(theme_color));
                    tv.setTextColor(Color.parseColor(theme_color));
                    //StatusBarUtil.setColor(MainActivity.this, ToolsUtils.getThemeColor(MainActivity.this), 0);
                }
            }
        });

        //刷新积分
        UserManager.getInstance().refresh();
    }

    /***
     * 初始化ViewPager
     */
    @SuppressLint("RestrictedApi")
    private void initViewPager() {
        mAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mFragments);
        mVpMain.setAdapter(mAdapter);
        mTabMain.setupWithViewPager(mVpMain);
        //设置阴影高度
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mTabMain.setElevation(0);
        }
        for (int i = 0; i < mTitles.size(); i++) {
            mTabMain.getTabAt(i).setCustomView(getTabView(i));
        }

        changeTabStatus(mTabMain.getTabAt(0), true);
        mTabMain.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //必须判断下fragment是否添加了，才能将进行请求布局的操作
                Fragment fragment = mFragments.get(tab.getPosition());
                /*if (fragment instanceof MineFragment) {
                    getWindow().setStatusBarColor(Color.parseColor("#F5F5F6"));
                    mFabTop.setVisibility(View.INVISIBLE);
                } else if (fragment instanceof HomeFragment)
                    getWindow().setStatusBarColor(ToolsUtils.getThemeColor(MainActivity.this) != 0 ?
                            ToolsUtils.getThemeColor(MainActivity.this) : ToolsUtils.getAttrValue(MainActivity.this));
                else
                    getWindow().setStatusBarColor(Color.parseColor("#FFFFFF"));*/


/*                if (fragment instanceof NewHomeFragment) {
                    StatusBarUtil.setFitSystemStatus(MainActivity.this, false);
                    StatusBarUtil.setImgTransparent(MainActivity.this);
                    *//*getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                    getWindow().setStatusBarColor(Color.TRANSPARENT);*//*

                } else if (fragment instanceof MineFragment) {
                    //StatusBarUtil.setFitSystemStatus(MainActivity.this, true);
                    StatusBarUtil.setColorNoTranslucentLightMode(MainActivity.this, Color.parseColor("#F5F5F6"));
                } else {
                    StatusBarUtil.setFitSystemStatus(MainActivity.this, true);
                    //StatusBarUtil.setTransparent(MainActivity.this);
                    StatusBarUtil.setColorNoTranslucentLightMode(MainActivity.this, Color.parseColor("#FFFFFF"));
                }*/

                if (fragment instanceof MineFragment) {
                    ((MineFragment) fragment).setTvTitleBackgroundColor(Color.parseColor("#F5F5F6"));
                } else if (fragment instanceof WxFragment) {
                    ((WxFragment) fragment).setTvTitleBackgroundColor(Color.parseColor("#FFFFFF"));
                } else if (fragment instanceof ProjectsFragment) {
                    ((ProjectsFragment) fragment).setTvTitleBackgroundColor(Color.parseColor("#FFFFFF"));
                } else if (fragment instanceof SystemFragment) {
                    ((SystemFragment) fragment).setTvTitleBackgroundColor(Color.parseColor("#FFFFFF"));
                }

                if (fragment.isAdded())
                    fragment.getView().requestLayout();
                changeTabStatus(tab, true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                changeTabStatus(tab, false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        /*if (ToolsUtils.getThemeColor(this) != 0) {
            StatusBarUtil.setColor(this, ToolsUtils.getThemeColor(this), 0);
            mFabTop.setBackgroundTintList(ColorStateList.valueOf(ToolsUtils.getThemeColor(this)));
        }*/
        //StatusBarUtil.setTranslucentForImageViewInFragment(MainActivity.this, null);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);

        //导航栏着色
        if (ToolsUtils.isOpenNavigationBar(this) && !ToolsUtils.getNightMode(this)) {
            Window window = getWindow();
            if (ToolsUtils.getThemeColor(this) != 0)
                window.setNavigationBarColor(ToolsUtils.getThemeColor(
                        this));
            else
                window.setNavigationBarColor(ToolsUtils.getAttrValue(this));
        }
        mFabTop.setOnClickListener(v -> {
            if (topRecyclerView != null)
                topRecyclerView.smoothScrollToPosition(0);
            mFabTop.setVisibility(View.INVISIBLE);
        });
        //有没有遇到过rv，在更新数据后，必须滑动下，才能看到改变？
        //收藏的功能，我取消收藏后，发了一个消息，然后通知碎片更新数据，但是发现没有更新数据，必须滑动下才行。
        //解决办法，就是tab的切换的时候碎片requestLayout一下就行了
        mVpMain.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    v.requestLayout();
                }
            }
        });
        mFabTop.setBackgroundTintList(ColorStateList.valueOf(ToolsUtils.getColor(this)));
    }

    /***
     * 初始化fragment和标题
     */
    private void initFragment() {
        mFragments = new ArrayList<>();
        mFragments.add(new NewHomeFragment());
        mFragments.add(new ProjectsFragment());
        mFragments.add(new SystemFragment());
        mFragments.add(new WxFragment());
        mFragments.add(new MineFragment());

        mTitles = new ArrayList<>();
        mTitles.add("首页");
        mTitles.add("项目");
        mTitles.add("分类");
        mTitles.add("公众号");
        mTitles.add("我的");
    }

    //设置图标
    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.tab_item, null);
        TextView mTxt_title = view.findViewById(R.id.tab_text);
        mTxt_title.setText(mTitles.get(position));
        ImageView img_title = view.findViewById(R.id.tab_image);
        img_title.setImageResource(tabIcons[position]);
        return view;
    }

    //改变状态
    private void changeTabStatus(TabLayout.Tab tab, boolean selected) {
        //获取到当前主题的颜色
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary,
                typedValue, true);

        View view = tab.getCustomView();
        if (view == null) return;
        TextView txtTitle = view.findViewById(R.id.tab_text);
        ImageView img_title = view.findViewById(R.id.tab_image);
        if (selected) {
            img_title.setImageResource(tabIconSelected[tab.getPosition()]);
            //Log.d("zxd", "changeTabStatus: " + typedValue.data);
            img_title.setColorFilter(typedValue.data);//可以改变一张图片的颜色，就不需要在资源文件中放那么多图片了，good
            txtTitle.setTextColor(typedValue.data);

            //如果选择了主题color，那么在tab切换的时候就需要安排颜色了
            String theme_color = (String) SPUtils.get(this, "theme_color", "");
            if (!TextUtils.isEmpty(theme_color)) {
                img_title.setColorFilter(Color.parseColor(theme_color));
                txtTitle.setTextColor(Color.parseColor(theme_color));
//                mTabMain.setTabTextColors(ColorStateList.valueOf(Color.parseColor(theme_color)));
//                mTabMain.setSelectedTabIndicatorColor(Color.parseColor(theme_color));
            }
        } else {
            img_title.setColorFilter(null);
            img_title.setImageResource(tabIcons[tab.getPosition()]);
            txtTitle.setTextColor(Color.parseColor("#333333"));
//            mTabMain.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#333333")));
//            mTabMain.setSelectedTabIndicatorColor(Color.parseColor("#333333"));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销
        RxBus.getDefault().unregister(this);
    }

    /***
     * 为了登录后能切换到首页，放在这里实现。接收事件里写这些，不能切换到首页
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        recreate();
        mVpMain.setCurrentItem(0);
    }

    //定义一个变量，来标识是否退出
    private static boolean isExit = false;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            //利用handler延迟发送更改状态信息
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @SuppressLint("RestrictedApi")
    @Override
    public void scrollType(boolean direction) {
        //上拉
        if (direction) {
            hasdown = true;
            //连续上拉，第一次有效
            if (hasup) {
                //mTabMain.setVisibility(View.GONE);
                mFabTop.setVisibility(View.INVISIBLE);
                ObjectAnimator o1 = ObjectAnimator.ofFloat(mTabMain, View.TRANSLATION_Y, 0, mTabMain.getHeight());
                ObjectAnimator o2 = ObjectAnimator.ofFloat(mTabMain, "alpha", 1f, 0f);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.setDuration(400);
                animatorSet.playTogether(o1, o2);
                animatorSet.start();
                hasup = false;
            }
        } else {//下滑
            hasup = true;
            //连续下滑，第一次有效
            if (hasdown) {
                mFabTop.setVisibility(View.VISIBLE);
                //mTabMain.setVisibility(View.VISIBLE);
                ObjectAnimator o1 = ObjectAnimator.ofFloat(mTabMain, View.TRANSLATION_Y, mTabMain.getHeight(), 0);
                ObjectAnimator o2 = ObjectAnimator.ofFloat(mTabMain, "alpha", 0f, 1f);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.setDuration(400);
                animatorSet.playTogether(o1, o2);
                animatorSet.start();
                hasdown = false;
            }
        }
    }

    @Override
    public void inTop(boolean top, RecyclerView recyclerView) {
        inTop = top;
        topRecyclerView = recyclerView;
    }

    //上拉状态
    private boolean hasup = true;
    //下滑状态
    private boolean hasdown = true;
    //是否在顶部
    private boolean inTop = true;
    //从fragment传递过来的recycleView
    private RecyclerView topRecyclerView;

    /**
     * 设置 app 不随着系统字体的调整而变化
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}
